<template>
  <div class="login">
    <el-card class="login-card">
      <h3 class="login-title">欢迎登录小说精品屋</h3>
      <div class="login-form">
        <el-form ref="ruleFormRef" :model="state" :rules="formRules">
          <el-form-item prop="username">
            <el-input v-model="username" placeholder="手机号码" prefix-icon="">
              <template #prefix>
                <i class="iconfont icon-weibiaoti562" style="color: #000;font-size: 25px"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="password" placeholder="密码" show-password type="password">
              <template #prefix>
                <i class="iconfont icon-mima" style="color: #000;font-size: 25px"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="velCode">
            <div class="login-vercode" style="display: flex;justify-content: space-between">
              <el-input v-model="velCode" placeholder="请输入验证码" style="width: 70%" type="password">
                <template #prefix>
                  <i class="iconfont icon-yanzhengma" style="color: #000;font-size: 25px"></i>
                </template>
              </el-input>
              <img
                  :src="imgVerifyCode"
                  style="cursor: pointer;"
                  @click="loadImgVerifyCode"
              />
            </div>

          </el-form-item>
          <el-form-item>
            <el-button :loading="isLoading" style="width: 100%" type="primary" @click="doLogin(ruleFormRef)">登录
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button style="width: 100%" type="primary" @click="resetForm(ruleFormRef)">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref, toRefs} from "vue";
import {getImgVerifyCode} from "@/api/resource";
import {ElMessage, type FormInstance, type FormRules} from "element-plus";
import {login} from "@/api/user";
import {useAuthStore} from "@/stores/auth";
import {useRoute, useRouter} from "vue-router";
import {useNavbarStore} from "@/stores/navbar";

const authStore = useAuthStore()
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const route = useRoute()
const isLoading = ref(false);
const state = reactive({
  username: '',
  password: '',
  imgVerifyCode: '',
  sessionId: '',
  velCode: '',
});
const {username, password, imgVerifyCode, velCode} = toRefs(state)
const navbarStore = useNavbarStore()
const doLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      try {
        const {data} = await login(state);
        //提示登录成功
        ElMessage.success('登录成功!');
        authStore.setToken(data.token);
        authStore.setUid(data.uid);
        authStore.setNickName(data.nickName);
        authStore.setUserPhoto(data.userPhoto);
        navbarStore.setActiveIndex('/home')
        router.push({path: "/"});
      } catch (error) {
      }
      isLoading.value = false;

    } else {
      console.log('error submit!')
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  console.log(formEl)
  if (!formEl) return
  formEl.resetFields()
}
const loadImgVerifyCode = async () => {
  const {data} = await getImgVerifyCode();
  state.imgVerifyCode = "data:image/png;base64," + data.img;
  state.sessionId = data.sessionId;
};

onMounted(async () => {
  loadImgVerifyCode();
});
/*表单校验规则定义*/
// 定义表单验证规则
const formRules: FormRules = {
  username: [
    {required: true, message: '手机号不能为空', trigger: ['blur', 'submit']},
    {validator: validateMobile, trigger: ['blur', 'submit']}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: ['blur', 'submit']},
    {min: 6, max: 20, message: '密码长度需在6到20位之间', trigger: ['blur', 'submit']},
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
      message: '密码必须包含字母和数字',
      trigger: ['blur', 'submit']
    }
  ],
  velCode: [
    {required: true, message: '验证码不能为空', trigger: ['blur', 'submit']}
  ]
};

function validateMobile(rule: any, value: string, callback: (error?: string) => void) {
  const phonePattern = /^1[3-9]\d{9}$/;
  if (!phonePattern.test(value)) {
    callback('请输入有效的手机号码');
  } else {
    callback();
  }
}
</script>

<style lang="scss" scoped>
.login {
  text-align: center;
  width: 60%;
  //border: 1px solid #000;
  margin: 0 auto;
  padding: 10px;

  .login-card {
    padding: 50px;
  }

  .login-title {
    padding-bottom: 50px;
    font-size: 30px;
  }

  .login-form {
    width: 30%;
    //border: 1px solid #000;
    text-align: center;
    margin: 0 auto;
  }
}

</style>
